//
//  AddMessageController.m
//  陶瓷
//
//  Created by 王戈 on 15/8/2.
//  Copyright (c) 2015年 王戈. All rights reserved.
//

#import "AddMessageController.h"
#import "InputInfoCellTableViewCell.h"
#import "TCTakePhotoCell.h"
#import "TCOptionCell.h"
#import "AddMessagePhotoViewCell.h"
#import "ZYQAssetPickerController.h"

@interface AddMessageController ()<UIImagePickerControllerDelegate ,UINavigationControllerDelegate ,UIActionSheetDelegate,UITextViewDelegate , ZYQAssetPickerControllerDelegate ,UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITextView *currentTF;
@property (nonatomic, strong) UIButton *cover;

//@property (nonatomic, strong) UIImage *photo;
//@property (nonatomic, weak) UIButton *photoBtn;
@property (nonatomic, copy) NSString *isSelling;
@property (nonatomic, assign) kTCMessageType type;

@property (nonatomic ,weak) AddMessagePhotoViewCell *photoCell;

@property (nonatomic, strong) UITableView *tableView;


@end

@implementation AddMessageController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (!self.answerDict.count) {
        self.answerDict = [NSMutableDictionary dictionaryWithCapacity:_questionArray.count];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(optionChanged:) name:OptionViewDidChoosedOptionNotification object:nil];
    
    [self setupSaveBtn];

    [self setupTableViewAndSendButton];
}

- (void)setupTableViewAndSendButton {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 49 - 64)];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.bounces = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    UIButton *button = [[UIButton alloc] init];
    button.backgroundColor = TCMainBGColor;
    [button setTitle:@"我要发布" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    [button.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
    button.height = 49;
    button.width = self.view.width;
    button.y = CGRectGetMaxY(_tableView.frame);
    [self.view addSubview:button];
}

- (UIButton *)cover {
    if (_cover == nil) {
        _cover = [[UIButton alloc] initWithFrame:self.view.bounds];
        _cover.backgroundColor = [UIColor clearColor];
    }
    return _cover;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.cover removeFromSuperview];
    [SVProgressHUD dismiss];
}

- (void)setupSaveBtn {
//    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeSystem];
//    saveBtn.frame = CGRectMake(0, 0, 30,30);
//    [saveBtn setTitle:@"提交" forState:UIControlStateNormal];
//    [saveBtn addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveBtn];
//    self.navigationItem.rightBarButtonItem = rightButtonItem;
}

- (void)sendMessage {
    [_currentTF resignFirstResponder];
    [SVProgressHUD showWithStatus:@"正在提交数据 请稍后.."];
    [self.view addSubview:self.cover];
    
    //    if (_photoCell.images.count) {
    // 有照片就上传后再提交
    // Santor 2015.9.5
    //        [[TCNetworkTool sharedNetTool] uploadImage:_photo andSuccessBlocks:^(NSString *successMessage) {
    //            [_answerDict setValue:successMessage forKey:@"0"];
    //            // 有 id 说明是编辑 没有id就是新加
    //            self.sid ? [self editMessage] : [self addMessage];
    //        } andFailureBlocks:^(NSString *failureMessage) {
    //            [MBHUDHelper showWarningWithText:failureMessage];
    //            [self.cover removeFromSuperview];
    //            [SVProgressHUD dismiss];
    //            return ;
    //        }];
    //    } else {
    // 没照片直接提交
    self.sid ? [self editMessage] : [self addMessage];
    //    }
}

- (void)editMessage {
    switch (_type) {
        case kTCMessageTypeRecruitment: // 招聘
        {
            [[TCNetworkTool sharedNetTool] recruitmentEditWithId:_sid andTitle:_answerDict[@"0"] andWage:_answerDict[@"1"] andAddress:_answerDict[@"6"] andPosition:_answerDict[@"2"] andContactNumber:_answerDict[@"4"] andRequirements:_answerDict[@"3"] andCompanyName:_answerDict[@"5"] andCompanyScale:_answerDict[@"7"] andCompanyFeature:_answerDict[@"8"] andLatitude:nil andLongitude:nil andState:nil andCreateTime:nil andIsTop:nil andUserId:nil andBrowseNumber:nil andCollectTimes:nil andAreaId:nil andWelfares:nil andSuccessBlocks:^(NSDictionary *dict) {
                
                [self successAndBack];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"EditSuccessNotification" object:dict];
                
            } andFailureBlocks:^(NSString *failureMessage) {
                [self failureAndStayWithMessage:failureMessage];
            }];
        }
            break;
        case kTCMessageTypeRent: // 商铺
        {
            [[TCNetworkTool sharedNetTool] rentEditWithID:_sid andTitle:_answerDict[@"1"] andPrice:_answerDict[@"2"] andArea:_answerDict[@"3"] andType:_answerDict[@"4"] andClostTo:nil andHistory:_answerDict[@"5"] andAddress:_answerDict[@"6"] andDescription:_answerDict[@"9"] andImageUrls:[_photoCell.images copy] andBrowseCount:nil andLatitude:nil andLongitude:nil andIsTop:nil andUserID:nil andCreatTime:nil andState:nil andAreaId:nil andCollectTimes:nil andLinkMan:_answerDict[@"7"] andContractNum:_answerDict[@"8"] SuccessBlocks:^(NSDictionary *dict) {
                
                [self successAndBack];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"EditSuccessNotification" object:dict];
                
            } andFailureBlocks:^(NSString *failureMessage) {
                [self failureAndStayWithMessage:failureMessage];
            }];
        }
            break;
        case kTCMessageTypeTailGoods: // 尾货
        {
            NSString *type = @"2";
            NSArray *array = _answerDict[@"8"];
            if (array.count == 1) {
                type = array.firstObject;
            }
            [[TCNetworkTool sharedNetTool] tailGoodsEditWithID:_sid andHeadImageUrls:[_photoCell.images copy] andBrand:_answerDict[@"1"] andStandard:_answerDict[@"2"] andCount:_answerDict[@"3"] andPrice:_answerDict[@"4"] andLinkMan:_answerDict[@"5"] andContactNumber:_answerDict[@"6"] andCompanyAddress:_answerDict[@"7"] andType:type andBrowseNumber:nil andLatitude:nil andLongitude:nil andUserId:nil andIsTop:nil andCreateTime:nil andState:nil andCollectTimes:nil andAreaId:nil andSuccessBlocks:^(NSDictionary *dict) {
                
                [self successAndBack];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"EditSuccessNotification" object:dict];
                
            } andFailureBlocks:^(NSString *failureMessage) {
                [self failureAndStayWithMessage:failureMessage];
            }];
        }
            break;
        default:
            break;
    }
}

- (void)addMessage {
    // 没有sid 说明是新增
    if ([self.title isEqualToString:@"招聘信息发布"]) {
        [[TCNetworkTool sharedNetTool] recruitmentAddWithId:nil andTitle:_answerDict[@"0"] andWage:_answerDict[@"1"] andAddress:_answerDict[@"6"] andPosition:_answerDict[@"2"] andContactNumber:_answerDict[@"4"] andRequirements:_answerDict[@"3"] andCompanyName:_answerDict[@"5"] andCompanyScale:_answerDict[@"7"] andCompanyFeature:_answerDict[@"8"] andLatitude:nil andLongitude:nil andState:nil andCreateTime:nil andIsTop:nil andUserId:nil andBrowseNumber:nil andCollectTimes:nil andAreaId:nil andWelfares:nil andSuccessBlocks:^(NSString *successMessage) {
            [self successAndBack];
        } andFailureBlocks:^(NSString *failureMessage) {
            [self failureAndStayWithMessage:failureMessage];
        }];
    } else if ([self.title isEqualToString:@"商铺信息发布"]) {
        [[TCNetworkTool sharedNetTool] rentAddWithID:nil andTitle:_answerDict[@"1"] andPrice:_answerDict[@"2"] andArea:_answerDict[@"3"] andType:_answerDict[@"4"] andClostTo:nil andHistory:_answerDict[@"5"] andAddress:_answerDict[@"6"] andDescription:_answerDict[@"9"] andImageUrls:[_photoCell.images copy] andBrowseCount:nil andLatitude:nil andLongitude:nil andIsTop:nil andUserID:nil andCreatTime:nil andState:nil andAreaId:nil andCollectTimes:nil andLinkMan:_answerDict[@"7"] andContractNum:_answerDict[@"8"] SuccessBlocks:^(NSString *successMessage) {
            [self successAndBack];
        } andFailureBlocks:^(NSString *failureMessage) {
            [self failureAndStayWithMessage:failureMessage];
        }];
        
    } else if ([self.title isEqualToString:@"尾货信息发布"]) {
        NSString *type = @"2";
        NSArray *array = _answerDict[@"8"];
        if (array.count == 1) {
            type = array.firstObject;
        }
        if (_answerDict.count < 8) {
            [SVProgressHUD dismiss];
            [self.cover removeFromSuperview];
            [MBHUDHelper showWarningWithText:@"请您输入完整的信息"];
            return;
        }
        [[TCNetworkTool sharedNetTool] tailGoodsAddWithHeadImageUrls:[_photoCell.images copy] andBrand:_answerDict[@"1"] andStandard:_answerDict[@"2"] andCount:_answerDict[@"3"] andPrice:_answerDict[@"4"] andLinkMan:_answerDict[@"5"] andContactNumber:_answerDict[@"6"] andCompanyAddress:_answerDict[@"7"] andType:type andBrowseNumber:nil andLatitude:nil andLongitude:nil andUserId:nil andIsTop:nil andCreateTime:nil andState:nil andCollectTimes:nil andAreaId:nil andSuccessBlocks:^(NSString *successMessage) {
            [self successAndBack];
        } andFailureBlocks:^(NSString *failureMessage) {
            [self failureAndStayWithMessage:failureMessage];
        }];
    }
}

- (void)successAndBack {
    [SVProgressHUD dismiss];
    [self.cover removeFromSuperview];
    [SVProgressHUD showSuccessWithStatus:@"更新成功!"];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)failureAndStayWithMessage:(NSString *)message {
    [SVProgressHUD dismiss];
    [self.cover removeFromSuperview];
    [MBHUDHelper showWarningWithText:message];
}

- (NSString *)answerWithIndex:(NSInteger)index {
    
    NSIndexPath *ip = [NSIndexPath indexPathForRow:index inSection:0];
    
    InputInfoCellTableViewCell *cell = (InputInfoCellTableViewCell *)[self.tableView cellForRowAtIndexPath:ip];
    
    return cell.answerTF.text ? cell.answerTF.text : @"";
}

#pragma mark - table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _questionArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ((_type == kTCMessageTypeRent || _type == kTCMessageTypeTailGoods) && indexPath.row == 0) {
        AddMessagePhotoViewCell *cell = [AddMessagePhotoViewCell cellWithTableView:tableView andImages:_answerDict[@"0"]];
        _photoCell = cell;
        [cell implementAddPhotoBlock:^{
            [self takePhoto];
        }];
        
        return cell;
    }else if (_type == kTCCollectTypeTailGoods && indexPath.row == 8) {
        TCOptionCell *cell = [TCOptionCell cellWithTableView:tableView];
        if (!_answerDict[@"8"]) {
            _answerDict[@"8"] = @[@"求购"];
        }
        cell.selectedOptions = [_answerDict[@"8"] mutableCopy];
        if (!cell.options) {
            cell.options = @[@"求购",@"出售"];
        }
        cell.textLabel.text = @"类型";
        return cell;
    }
    
    
    InputInfoCellTableViewCell *cell = [InputInfoCellTableViewCell cellWithTableView:tableView];
    cell.nameLabel.text = _questionArray[indexPath.row];
    cell.answerTF.text = [self.answerDict valueForKey:[NSString stringWithFormat:@"%ld",(long)indexPath.row]];
    cell.answerTF.delegate = self;
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ((_type == kTCMessageTypeRent || _type == kTCMessageTypeTailGoods) && indexPath.row == 0) {
        return kAddMessagePhotoViewCellHeight;
    }
    
    return 55;
}

#pragma mark - UITextFieldDelegate

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    _currentTF = textView;
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    InputInfoCellTableViewCell *cell = [self getCellWithTextField:textView];
    NSString *value = [textView.text ? textView.text : @"" stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [_answerDict setValue:value forKey:[NSString stringWithFormat:@"%ld",(long)[self.tableView indexPathForCell:cell].row]];
    
    _currentTF = nil;
}

//- (BOOL)textFieldShouldReturn:(UITextField *)textField {
//    InputInfoCellTableViewCell *cell = [self getCellWithTextField:textField];
//
//    NSInteger index = [_questionArray indexOfObject:cell.nameLabel.text];
//    if (index == _questionArray.count - 1) {
//        index = 0;
//    } else {
//        index += 1;
//    }
//
//    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
//    InputInfoCellTableViewCell *nextCell = (InputInfoCellTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
//    [nextCell.answerTF becomeFirstResponder];
//
//    return YES;
//}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    textView.text = [NSString stringWithFormat:@"%@\n",textView.text];
    
    return YES;
}

- (InputInfoCellTableViewCell *)getCellWithTextField:(UITextView *)textField {
    // 之所以有的再取次父类 有的只取两次 ,是因为在iOS7中 contentView 的父类是UITableViewCellScrollView这么个鬼 ,而且竟然不开放 .. 太傻比
    UIView *mayBeCell = (InputInfoCellTableViewCell *)[[textField superview] superview];
    if ([[mayBeCell class] isSubclassOfClass:[InputInfoCellTableViewCell class]]) {
        return (InputInfoCellTableViewCell *)mayBeCell;
    } else {
        return (InputInfoCellTableViewCell *)[mayBeCell superview];
    }
}

#pragma mark - scroll view delegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [_currentTF resignFirstResponder];
}

- (void)setQuestionArray:(NSArray *)questionArray {
    _questionArray = questionArray;
    if ([questionArray isEqualToArray:recruitmentQuestionArray]) {
        _type = kTCMessageTypeRecruitment;
    } else if ([questionArray isEqualToArray:rentQuestionArray]) {
        _type = kTCMessageTypeRent;
    } else if ([questionArray isEqualToArray:tailGoodsQuestionArray]) {
        _type = kTCMessageTypeTailGoods;
    }
}

#pragma mark - take photo

- (void)takePhoto {
    UIActionSheet *as = [[UIActionSheet alloc] initWithTitle:@"更改头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"打开相册", nil];
    [as showInView:self.view];
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [self openCamera];
    } else if (buttonIndex == 1){
        [self openAlbum];
    } else{
        
    }
}

/**
 *  打开照相机
 */
- (void)openCamera
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return;
    
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
    ipc.delegate = self;
    [self presentViewController:ipc animated:YES completion:nil];
}
/**
 *  打开相册
 */
- (void)openAlbum {
    
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
    
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
    
    picker.maximumNumberOfSelection = 6 - _photoCell.images.count;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups = NO;
    picker.delegate = self;
    
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
            return duration >= 5;
        } else {
            return YES;
        }
    }];
    
    [self presentViewController:picker animated:YES completion:NULL];
    //    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
    //
    //    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    //    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    //    ipc.delegate = self;
    //    [self presentViewController:ipc animated:YES completion:nil];
}

#pragma mark - ZYQAssetPickerController Delegate
- (void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
    for (int i = 0; i < assets.count; i++) {
        ALAsset *asset = assets[i];
        
        UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        [_photoCell.images addObject:tempImg];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 刷新
            [_photoCell refreshPhotos];
        });
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kTakePhotoCompletNotification object:image userInfo:@{kCompletedPhoto : image} ];
}

#pragma mark - option view notification
- (void)optionChanged:(NSNotification *)noti {
    _answerDict[@"8"] = noti.userInfo[OptionViewCurrentOption];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
